<script setup lang="ts">
import { ref, onMounted, watch, onBeforeUnmount } from 'vue'
import { MessageOutlined, QuestionCircleOutlined } from '@ant-design/icons-vue'
import * as echarts from 'echarts'
import 'echarts-wordcloud'
import { getTechFieldAndPositionUsingGet } from '@/api/positionController'
import { message } from 'ant-design-vue'
import {
  getCommonInterviewExperienceListUsingGet,
  getTecInterviewTechStackCountUsingPost,
  getTecInterviewTechStackQuestionUsingPost,
  submitInterviewExperienceCommentUsingPost,
  submitInterviewExperienceUsingPost,
} from '@/api/communityController'
import defaultAvatar from '@/assets/default.jpg'

// 选择公司
const company = ref('')
//选择技能领域id
const techFieldId = ref('')
//选择面试岗位id
const positionId = ref('')

//临时记录岗位
let tempPositionList = []
// 技术领域
const techFieldList = ref<any[]>([])
// 面试岗位
const positionList = ref<any[]>([])

const publishLoading = ref(false)

const companyList = ref([
  { value: '阿里巴巴', label: '阿里巴巴' },
  { value: '科大讯飞', label: '科大讯飞' },
  { value: '腾讯', label: '腾讯' },
  { value: '字节跳动', label: '字节跳动' },
  { value: '华为', label: '华为' },
  { value: '百度', label: '百度' },
  { value: '美团', label: '美团' },
  { value: '拼多多', label: '拼多多' },
])

// 面经列表数据
const loading = ref(false)
const experienceList = ref([])

// 发布面经表单数据
const newExperience = ref({
  company: '',
  techFieldId: '',
  positionId: '',
  content: '',
})

// 面试题列表数据
const questionsLoading = ref(false)
const questionList = ref<any[]>([])
const selectedTech = ref('')

const wordcloudRef = ref(null)
let wordcloudChart: any = null

// 技术栈数据
const techStackData = ref<any[]>([])

// 标签页状态
const activeTab = ref('experience')

// 监听标签页变化
const handleTabChange = (key: string) => {
  console.log('Tab changed to:', key)
  if (key === 'interview') {
    // 切换到面试题库标签时，如果已有数据则渲染词云图
    if (techStackData.value.length > 0) {
      setTimeout(() => {
        renderWordcloud()
      }, 300)
    }
  }
}

// for share experience form
const sharePositionList = ref<any[]>([])
const handleShareTechFieldChange = (value: any) => {
  sharePositionList.value = []
  newExperience.value.positionId = ''
  // 获取岗位信息
  if (tempPositionList) {
    tempPositionList.filter((item: any) => {
      if (value === item.techFieldId) {
        sharePositionList.value.push({ value: item.id, label: item.name })
      }
    })
  }
}

// 评论相关变量
const commentVisible = ref<Record<number, boolean>>({})
const newComment = ref<string>()
const showComments = (id: number) => {
  commentVisible.value[id] = !commentVisible.value[id]
}
//获取面经
const fetchInterviewExperience = async () => {
  const data = await getCommonInterviewExperienceListUsingGet()
  if (data.code === 0) {
    message.success('获取面试成功')
  } else {
    message.error('获取面试失败')
  }

  experienceList.value = data.data as any
}
// 发布面经
const publishExperience = async () => {
  if (!newExperience.value.company || newExperience.value.company?.trim() === '') {
    message.warning('面试公司不能为空')
    return
  }
  if (!newExperience.value.techFieldId) {
    message.warning('技术领域不能为空')
    return
  }
  if (!newExperience.value.positionId) {
    message.warning('面试岗位不能为空')
    return
  }
  if (!newExperience.value.content || newExperience.value.content.trim() === '') {
    message.warning('面经内容不能为空')
    return
  }
  publishLoading.value = true

  // 调用API发布面经
  const data = await submitInterviewExperienceUsingPost({
    company: newExperience.value.company,
    techFieldId: newExperience.value.techFieldId,
    positionId: newExperience.value.positionId,
    content: newExperience.value.content,
  })
  if (data.data) message.success('发布面经成功')
  else message.error('发布面经失败')

  publishLoading.value = false
  isPublishExpanded.value = false

  // 重置面经内容表单
  newExperience.value = {
    company: '',
    techFieldId: '',
    positionId: '',
    content: '',
  }

  //重新获取面经
  await fetchInterviewExperience()
}

//提交评论
const submitComment = async (item: any) => {
  if (!newComment.value || newComment.value.trim() === '') {
    message.warning('评论内容不能为空')
    return
  }

  //发送请求添加评论内容
  const data = await submitInterviewExperienceCommentUsingPost({
    interviewExperienceId: item.id,
    content: newComment.value,
  })
  if (data.data) {
    message.success('评论成功')
  } else {
    message.error('评论失败')
  }
  // 清空评论框
  newComment.value = ''
  //重新获取面经数据
  await fetchInterviewExperience()
}

// ==========================================================

// 渲染词云图
const renderWordcloud = () => {
  if (!wordcloudRef.value || techStackData.value.length === 0) return

  // 准备词云数据
  const cloudData = techStackData.value.map((item) => ({
    name: item.techStack,
    value: item.count * 1000, // 放大数值使词云更明显
  }))

  // 确保DOM元素已经挂载
  if (!wordcloudRef.value) {
    console.error('词云图DOM元素未找到')
    return
  }

  // 初始化或重用词云图
  try {
    // 每次渲染前先销毁旧的图表实例
    if (wordcloudChart) {
      wordcloudChart.dispose()
      wordcloudChart = null
    }

    // 创建新的图表实例
    wordcloudChart = echarts.init(wordcloudRef.value)

    const option = {
      series: [
        {
          type: 'wordCloud',
          shape: 'circle',
          left: 'center',
          top: 'center',
          width: '80%',
          height: '80%',
          right: null,
          bottom: null,
          sizeRange: [14, 60],
          rotationRange: [-45, 45],
          rotationStep: 15,
          gridSize: 8,
          drawOutOfBound: false,
          textStyle: {
            fontFamily: 'sans-serif',
            fontWeight: 'bold',
            color: function () {
              return (
                'rgb(' +
                [
                  Math.round(Math.random() * 160),
                  Math.round(Math.random() * 160),
                  Math.round(Math.random() * 160),
                ].join(',') +
                ')'
              )
            },
          },
          emphasis: {
            textStyle: {
              shadowBlur: 10,
              shadowColor: '#333',
            },
          },
          data: cloudData,
        },
      ],
    }

    wordcloudChart.setOption(option)

    // 点击词云图事件
    wordcloudChart.off('click')
    wordcloudChart.on('click', function (params: any) {
      selectedTech.value = params.name
      //加载面试题
      loadQuestions(params.name)
    })
  } catch (error) {
    console.error('渲染词云图出错:', error)
    message.error('渲染词云图出错，请刷新页面重试')
  }
}

// 加载面试题
const loadQuestions = async (tech: string) => {
  questionsLoading.value = true

  try {
    //发送请求获取公司岗位技术栈对应的面试题
    const response = await getTecInterviewTechStackQuestionUsingPost({
      company: company.value,
      positionId: positionId.value as any,
      techStack: tech,
    })

    if (response.code === 0 && response.data) {
      questionList.value = response.data as any[]
    } else {
      message.error('获取面试题失败：' + (response.message || '未知错误'))
      // 使用模拟数据作为备份
      questionList.value = [
        {
          id: '1',
          title: `${tech}基础知识点总结`,
          answer: `在使用${tech}时，需要注意以下几点：\n1. 合理设计架构\n2. 注重代码质量\n3. 考虑性能优化\n4. 做好异常处理\n5. 编写完善的文档`,
          techStackId: '1',
        },
        {
          id: '2',
          title: `${tech}在实际项目中的应用场景`,
          answer: `${tech}在实际项目中主要应用于以下场景：\n1. 高并发系统的性能优化\n2. 复杂业务逻辑的简化\n3. 跨平台应用开发\n4. 数据处理和分析\n5. 系统架构升级和重构`,
          techStackId: '1',
        },
      ]
    }
  } catch (error) {
    console.error('获取面试题出错:', error)
    message.error('获取面试题出错，请稍后重试')
    // 使用模拟数据作为备份
    questionList.value = [
      {
        id: '1',
        title: `${tech}基础知识点总结`,
        answer: `在使用${tech}时，需要注意以下几点：\n1. 合理设计架构\n2. 注重代码质量\n3. 考虑性能优化\n4. 做好异常处理\n5. 编写完善的文档`,
        techStackId: '1',
      },
      {
        id: '2',
        title: `${tech}在实际项目中的应用场景`,
        answer: `${tech}在实际项目中主要应用于以下场景：\n1. 高并发系统的性能优化\n2. 复杂业务逻辑的简化\n3. 跨平台应用开发\n4. 数据处理和分析\n5. 系统架构升级和重构`,
        techStackId: '1',
      },
    ]
  } finally {
    questionsLoading.value = false
  }
}

// 监听窗口大小变化，重绘词云图
const handleResize = () => {
  if (wordcloudChart) {
    wordcloudChart.resize()
  }
}

window.addEventListener('resize', handleResize)

//修改面试领域后的回调函数
const handleTechFieldChange = (value: any) => {
  positionList.value = []
  positionId.value = ''
  // 获取岗位信息
  tempPositionList.filter((item: any) => {
    if (value === item.techFieldId) {
      positionList.value.push({ value: item.id, label: item.name })
    }
  })
}

//获取技术领域信息和岗位信息
const fetchTechFieldAndPosition = async () => {
  try {
    const data = await getTechFieldAndPositionUsingGet()
    if (data.code === 0) {
      //  { value: id, label: '前端开发工程师' },  将技术领域给我转换为如下的选项
      data.data.techFieldList.map((item: any) => {
        techFieldList.value.push({ value: item.id, label: item.name })
      })
      tempPositionList = data.data.positionList
    } else {
      message.error('获取技术领域信息和岗位信息失败！' + data?.message)
    }
  } catch (error) {
    console.error('获取技术领域和岗位信息出错:', error)
    message.error('获取技术领域和岗位信息失败')
  }
}

// 获取技术栈数据
const fetchTechStackData = async () => {
  try {
    const response = await getTecInterviewTechStackCountUsingPost({
      company: company.value,
      techFieldId: techFieldId.value as any,
      positionId: positionId.value as any,
    })

    if (response.code === 0) {
      techStackData.value = response.data as any
      console.log('techStackData', techStackData.value)

      // 使用nextTick确保DOM已更新
      setTimeout(() => {
        renderWordcloud()
      }, 300)
    } else {
      message.error('获取技术栈数据失败：' + response.message)
    }
  } catch (error) {
    console.error('获取技术栈数据出错：', error)
    message.error('获取技术栈数据出错')

    // 使用模拟数据（仅在API调用失败时使用）
    techStackData.value = [
      { id: '1', techStack: 'Java基础', count: 4 },
      { id: '2', techStack: '并发编程', count: 3 },
      { id: '3', techStack: 'JVM', count: 5 },
      { id: '4', techStack: 'MySQL', count: 2 },
      { id: '5', techStack: 'Redis', count: 6 },
      { id: '6', techStack: 'Spring框架', count: 3 },
      { id: '7', techStack: '系统设计', count: 2 },
      { id: '8', techStack: '操作系统与网络', count: 4 },
      { id: '9', techStack: '算法', count: 1 },
    ]

    // 使用nextTick确保DOM已更新
    setTimeout(() => {
      renderWordcloud()
    }, 300)
  }
}

const isPublishExpanded = ref(false)
const shareExperienceRef = ref<any>(null)

const toggleShareExperience = () => {
  isPublishExpanded.value = !isPublishExpanded.value
}

const handleClickOutside = (event: MouseEvent) => {
  const target = event.target as Element
  if (shareExperienceRef.value && shareExperienceRef.value.contains(target)) {
    return
  }
  if (target.closest && target.closest('.ant-select-dropdown')) {
    return
  }
  if (isPublishExpanded.value) {
    isPublishExpanded.value = false
  }
}

// 组件卸载时销毁图表和事件监听
onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize)
  if (wordcloudChart) {
    wordcloudChart.dispose()
    wordcloudChart = null
  }
  document.removeEventListener('mousedown', handleClickOutside)
})

// 组件挂载时初始化
onMounted(() => {
  fetchInterviewExperience()
  fetchTechFieldAndPosition()
  document.addEventListener('mousedown', handleClickOutside)

  // 给DOM一点时间加载
  setTimeout(() => {
    if (activeTab.value === 'interview' && techStackData.value.length > 0) {
      renderWordcloud()
    }
  }, 500)
})

// 监听岗位ID变化，获取技术栈数据
watch(
  () => [positionId.value, company.value, techFieldId.value],
  () => {
    if (positionId.value) {
      fetchTechStackData()
    } else {
      // 清空技术栈数据，避免显示旧数据
      techStackData.value = []

      // 如果有图表实例，销毁它
      if (wordcloudChart) {
        wordcloudChart.dispose()
        wordcloudChart = null
      }
    }
  }
)
</script>

<template>
  <div class="community-container">
    <!-- 主要内容区域 -->
    <div class="content-area">
      <a-tabs v-model:activeKey="activeTab" @change="handleTabChange">
        <!-- 面经分享标签页 -->
        <a-tab-pane key="experience" tab="面经分享">
          <div class="experience-section">
            <!-- 面经内容列表 -->
            <div class="experience-list">
              <a-list :data-source="experienceList" :loading="loading" item-layout="vertical">
                <template #renderItem="{ item }">
                  <a-list-item>
                    <a-list-item-meta>
                      <template #title>
                        <div class="author-info">
                          <a-avatar :src="item.userAvatar ?? defaultAvatar" :size="40" />
                          <div class="author-detail">
                            <div class="author-name">{{ item.userName }}</div>
                            <div class="post-time">{{ item.createTime }}</div>
                          </div>
                        </div>
                      </template>
                    </a-list-item-meta>
                    <div class="experience-title">{{ item.title }}</div>
                    <div class="experience-content">{{ item.content }}</div>
                    <div class="experience-footer">
                      <div class="action-btn" @click="showComments(item.id)">
                        <MessageOutlined />
                        评论 ({{ item.commentCount }})
                      </div>
                    </div>

                    <!-- 评论区 -->
                    <div v-if="commentVisible[item.id]" class="comment-section">
                      <!-- 已有评论 -->
                      <div v-if="item.commentCount > 0" class="comment-list">
                        <div
                          v-for="(comment, index) in item.comments"
                          :key="index"
                          class="comment-item"
                        >
                          <a-avatar :src="comment.userAvatar ?? defaultAvatar" :size="32" />
                          <div class="comment-body">
                            <div class="author-detail">
                              <div class="author-name" style="font-size: 14px">
                                {{ comment.userName }}
                              </div>
                              <div class="post-time">{{ comment.createTime }}</div>
                            </div>
                            <div class="comment-content-text">{{ comment.content }}</div>
                          </div>
                        </div>
                      </div>
                      <div v-else class="no-comments">暂无评论，快来发表你的观点吧</div>

                      <!-- 评论输入框 -->
                      <div class="comment-input">
                        <a-textarea
                          v-model:value="newComment"
                          placeholder="写下你的评论..."
                          :rows="3"
                        />
                        <a-button type="primary" class="submit-btn" @click="submitComment(item)">
                          发表评论
                        </a-button>
                      </div>
                    </div>
                  </a-list-item>
                </template>
              </a-list>
            </div>

            <!-- 固定在底部的分享面经组件 -->
            <div
              ref="shareExperienceRef"
              class="fixed-share-experience"
              :class="{ expanded: isPublishExpanded }"
            >
              <div class="share-form" v-show="isPublishExpanded">
                <a-form layout="vertical">
                  <div class="share-form-row">
                    <a-form-item label="面试公司" style="flex: 1">
                      <a-input v-model:value="newExperience.company" placeholder="请输入面试公司" />
                    </a-form-item>
                    <a-form-item label="技术领域" style="flex: 1">
                      <a-select
                        v-model:value="newExperience.techFieldId"
                        placeholder="请选择技术领域"
                        :options="techFieldList"
                        style="width: 150px"
                        @change="handleShareTechFieldChange"
                      ></a-select>
                    </a-form-item>
                    <a-form-item label="面试岗位" style="flex: 1">
                      <a-select
                        v-model:value="newExperience.positionId"
                        placeholder="请选择岗位"
                        style="width: 150px"
                        :options="sharePositionList"
                      ></a-select>
                    </a-form-item>
                  </div>
                  <a-form-item label="内容">
                    <a-textarea
                      v-model:value="newExperience.content"
                      placeholder="分享你的面试经验，帮助其他求职者..."
                      :rows="4"
                    />
                  </a-form-item>
                  <a-form-item>
                    <a-button type="primary" @click="publishExperience" :loading="publishLoading">
                      发布面经
                    </a-button>
                  </a-form-item>
                </a-form>
              </div>

              <div class="share-header" @click="toggleShareExperience">
                <h3>分享你的面试经验</h3>
                <div class="expand-hint">
                  {{ isPublishExpanded ? '点击收起' : '点击展开' }}
                </div>
              </div>
            </div>
          </div>
        </a-tab-pane>

        <!-- 面试题库标签页 -->
        <a-tab-pane key="interview" tab="面试题库">
          <div class="interview-section">
            <!-- 公司和岗位选择 - 水平布局 -->
            <a-form layout="inline" class="form-inline">
              <a-form-item label="面试公司">
                <a-select
                  v-model:value="company"
                  :options="companyList"
                  placeholder="请选择公司"
                  style="width: 150px"
                  allow-clear
                />
              </a-form-item>
              <a-form-item label="技术领域">
                <a-select
                  v-model:value="techFieldId"
                  placeholder="请选择技术领域"
                  :options="techFieldList"
                  style="width: 150px"
                  @change="handleTechFieldChange"
                ></a-select>
              </a-form-item>
              <a-form-item label="面试岗位">
                <a-select
                  v-model:value="positionId"
                  placeholder="请选择岗位"
                  :options="positionList"
                  style="width: 150px"
                ></a-select>
              </a-form-item>
            </a-form>

            <!-- 技术栈词云图 -->
            <div v-if="techStackData.length > 0" class="wordcloud-section">
              <h3>热点技术栈</h3>
              <div ref="wordcloudRef" class="wordcloud-container"></div>
            </div>
            <div v-else-if="positionId && !techStackData.length" class="empty-data">
              <a-empty description="当前没有这个公司岗位的技术题库" />
            </div>

            <!-- 面试题列表 - 动态渲染 -->
            <div v-if="questionList.length > 0" class="questions-section">
              <div class="section-header">
                <h3>{{ selectedTech }} 相关面试题</h3>
              </div>

              <a-spin :spinning="questionsLoading">
                <div class="interview-questions">
                  <div v-for="item in questionList" :key="item.id" class="question-card">
                    <QuestionCircleOutlined class="question-icon" />
                    <div class="question-title">{{ item.title }}</div>
                  </div>
                </div>
              </a-spin>
            </div>
          </div>
        </a-tab-pane>
      </a-tabs>
    </div>
  </div>
</template>

<style scoped>
.community-container {
  display: flex;
  width: 100%;
  min-height: 100%;
  padding: 20px;
}

/* 主要内容区域 */
.content-area {
  flex: 1;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  padding: 20px;
}

/* 发布面经表单样式 */
.publish-experience {
  background-color: #f9f9f9;
  padding: 20px;
  border-radius: 8px;
  border: 1px solid #eee;
}

.publish-experience h3 {
  margin-bottom: 16px;
  color: #1890ff;
}

/* 面经列表样式 */
.experience-list {
  margin-bottom: 80px; /* 为底部分享面经表单留出空间 */
}

.author-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.author-detail {
  display: flex;
  flex-direction: column;
}

.author-name {
  font-weight: 500;
  font-size: 16px;
}

.post-time {
  font-size: 12px;
  color: #999;
}

.experience-title {
  font-size: 18px;
  font-weight: bold;
  margin: 12px 0;
}

.experience-content {
  color: #666;
  margin-bottom: 16px;
  line-height: 1.6;
}

.experience-footer {
  display: flex;
  margin-bottom: 12px;
}

.action-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  color: #666;
  cursor: pointer;
}

.action-btn:hover {
  color: #1890ff;
}

/* 评论区样式 */
.comment-section {
  margin-top: 20px;
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.comment-list {
  margin-bottom: 15px;
}

.comment-item {
  display: flex;
  gap: 12px;
  padding: 12px 0;
  border-bottom: 1px solid #eee;
}

.comment-item:last-child {
  border-bottom: none;
}

.comment-body {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.comment-content-text {
  color: #333;
  line-height: 1.6;
}

.comment-user {
  font-weight: 500;
  color: #333;
}

.comment-content {
  margin: 5px 0;
}

.comment-time {
  font-size: 12px;
  color: #999;
}

.no-comments {
  color: #999;
  font-style: italic;
  margin-bottom: 15px;
}

.comment-input {
  margin-top: 10px;
}

.submit-btn {
  margin-top: 10px;
  float: right;
}

/* 表单水平布局 */
.form-inline {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  margin-bottom: 20px;
}

/* 面试题库样式 */
.wordcloud-section {
  height: 450px;
  margin: 20px 0;
  border: 1px solid #eee;
  border-radius: 8px;
  padding: 20px;
  background-color: #fafafa;
}

.wordcloud-container {
  width: 100%;
  height: 380px;
  position: relative;
}

.empty-data {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
  margin: 20px 0;
  border: 1px solid #eee;
  border-radius: 8px;
  background-color: #fafafa;
}

/* 问题卡片样式 */
.interview-questions {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.question-card {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px 20px;
  border: 1px solid #e8e8e8;
  border-radius: 8px;
  background-color: #fff;
  transition: transform 0.2s ease, box-shadow 0.2s ease;
  cursor: pointer;
}

.question-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.question-icon {
  color: #1890ff;
  font-size: 18px;
  flex-shrink: 0;
}

.question-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.section-header {
  margin-bottom: 16px;
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
}

/* 固定在底部的分享面经组件 */
.fixed-share-experience {
  position: fixed;
  bottom: 0;
  left: 280px; /* 左侧菜单宽度 */
  right: 0;
  background: #fff;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  z-index: 100;
  transition: all 0.35s ease;
  display: flex;
  flex-direction: column-reverse;
  max-height: 50px;
  overflow: hidden;
  border-top: 1px solid #eaeaea;
}

.fixed-share-experience.expanded {
  max-height: 450px; /* 增加高度确保内容完全显示 */
}

.share-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  height: 50px;
  cursor: pointer;
  background: linear-gradient(145deg, #f8faff, #f0f5ff);
  flex-shrink: 0; /* 防止被压缩 */
}

.share-header h3 {
  margin: 0;
  color: #1890ff;
  font-size: 16px;
  font-weight: 500;
}

.expand-hint {
  font-size: 12px;
  color: #999;
}

.share-form-row {
  display: flex;
  gap: 16px;
  align-items: flex-start;
}

.share-form {
  padding: 20px;
  background-color: #fff;
  border-top: 1px solid #eaeaea;
  overflow-y: auto; /* 如果内容过多可以滚动 */
  max-height: 400px; /* 限制最大高度 */
}
</style>
